<template>
  <view class="im-message-list">
    <view class="cu-list menu-avatar" :style="{ paddingBottom: paddingB + 'px' }" v-if="msgsIn.length > 0">
      <template v-for="(item, index) in msgsIn" :key="index">
        <view
          v-if="!item.is_hide"
          class="cu-item cu-item-1"
          :class="[
            modalName == 'move-box-' + index ? 'move-cur' : '',
            item.is_top == 1 ? 'top-contacts' : '',
            'third',
            // item.is_group == 0 ? 'third' : 'second'
          ]"
          @touchstart="ListTouchStart"
          @touchmove="ListTouchMove"
          @touchend="ListTouchEnd"
          @tap="openChat(index, item)"
          :data-target="'move-box-' + index"
        >
          <view
            class="cu-avatar lg cu-header-img"
            :class="appSetting.circleAvatar ? 'round' : 'radius-16'"
            :style="[{ backgroundImage: 'url(' + item.avatar + '?imageView2/1/w/100/h/100/q/100' + ')' }]"
          >
            <statusPoint
              class="status-point"
              v-if="item.is_online /*&& item.is_group == 0*/ && globalConfig.chatInfo.online == 1"
              type="success"
            ></statusPoint>
          </view>
          <view class="content">
            <view class="c-333">
              <Tags v-if="item.is_group == 1" text="群聊" size="mini"></Tags>
              <Tags v-if="item.tempChat" text="临时" size="mini"></Tags>
              <!-- <statusPoint
              v-if="item.is_online && item.is_group == 0 && globalConfig.chatInfo.online == 1"
              type="success"
            ></statusPoint> -->
              <view class="text-overflow f-16 f-w item-level__wrap" style="width: 80%; color: #202020">
                {{ item.displayName || item.realname }}
                <!-- <image
									class="level-icon"
									v-if="item.level?.icon"
									:src="item.level.icon"
									mode="widthFix"
								/> -->
                <view class="level-icon-wrap" v-if="item.level?.icon">
                  <image class="level-icon" :src="item.level?.icon" mode="widthFix" />
                  {{ item.level?.name }}
                </view>
                <template v-if="item.is_group == 1">({{ item.num }})</template>
              </view>
            </view>

            <view class="im-flex im-justify-content-start im-align-items-start pt-5">
              <view class="text-gray text-sm">
                <text v-if="item.unread > 0 && item.is_notice == 0">[{{ item.unread }}条未读]&nbsp;</text>
              </view>
              <mp-html
                :content="emojiToHtml(item.lastContent, item)"
                class="im-flex text-overflow no-click fs-26 mp-html-wrap"
                style="color: #acacac"
              />
            </view>
          </view>
          <view class="action">
            <!-- <view class="text-grey text-xs">{{ from_time(item.lastSendTime) }}</view> -->
            <view class="cu-tag round bg-pink sm" v-if="item.unread > 0 && item.is_notice">
              {{ item.unread }}
            </view>
            <view class="c-999" v-if="item.is_notice == 0">
              <text class="cuIcon-musicforbidfill"></text>
            </view>
          </view>
          <!-- :class="item.is_group == 0 ? 'third' : 'second'" -->
          <view class="move third">
            <view class="bg-grey" v-if="item.is_top == 1" @tap="btnTap(0, item)">取消置顶</view>
            <view class="bg-blue" v-else @tap="btnTap(0, item)">置顶聊天</view>
            <view class="bg-orange" v-if="item.is_notice == 1" @tap="btnTap(2, item)">免扰</view>
            <view class="bg-orange" v-else @tap="btnTap(2, item)">取消免扰</view>
            <!-- v-if="item.is_group == 0" -->
            <view class="bg-red" @tap="btnTap(1, item)">删除会话</view>
          </view>
          <text class="last-time fs-22">{{ tiemForat(item.lastSendTime) }}</text>
        </view>
      </template>
    </view>
    <Empty v-else noDatatext="暂无聊天" textcolor="#999" />
  </view>
</template>

<script>
import emoji from "@/utils/emoji.js";
import statusPoint from "./status.vue";
import { useloginStore } from "@/store/login";
import pinia from "@/store/index";
const userStore = useloginStore(pinia);
export default {
  name: "message-list",
  props: {
    msgs: {
      type: Array,
      default: function () {
        return [];
      },
    },
    btnWidth: { type: Number, default: 320 },
  },
  components: {
    statusPoint,
  },
  data() {
    return {
      msgsIn: [],
      damping: 0.29,
      moveIndex: -1,
      x: 0,
      oX: 0,
      scY: true,
      btnWidthpx: 160,
      touchStart: false,
      modalName: null,
      listTouchStart: 0,
      listTouchDirection: null,
      emojiMap: [],
      chatStatus: true,
      paddingB: 0,
      appSetting: userStore.appSetting,
      globalConfig: userStore.globalConfig,
      userInfo: userStore.userInfo,
    };
  },
  created() {
    this.init(this.msgs);
    this.btnWidthpx = uni.upx2px(this.btnWidth) * -1 + 2;
    const emoji = uni.getStorageSync("emojiList");
    // 解析所有表情
    emoji.forEach((item) => {
      if (item.id === 1) {
        item.emoji.forEach((it) => {
          this.emojiMap[it.id] = it.path;
        });
      }
    });
    // #ifdef H5
    this.paddingB = this.navBarHeight + this.inlineTools;
    // #endif

    // #ifndef H5
    this.paddingB = this.navBarHeight + this.inlineTools;
    // #endif
  },
  watch: {
    msgs: function (nv) {
      this.init(nv);
    },
  },
  methods: {
    init: function (msgs) {
      this.moveIndex = -1;
      this.msgsIn = msgs.filter((obj) => obj.lastContent);
    },
    scrolltolower: function () {},
    // 自动解析消息中的表情
    emojiToHtml(str, item) {
      /**
       * item.age_max 不存在年龄或者最大限制年龄为0 表示不限制
       * item.sex == 3 表示不限制
       */
      if (Number(item.is_group) == 1) {
        if (!!item.age_max || item.sex != 3) {
          if (item.sex != this.userInfo.sex) {
            if (item.sex == this.userInfo.sex && this.userInfo.age < item.age_min && this.userInfo.age > item.age_max) {
              item.unread = item.unread - 1;
              return;
            }
          }
        }
      }

      if (!str) {
        return;
      }

      let st = "";

      if (item.type === "location") {
        st = "[位置信息]";
      } else if (item.type === "usercard") {
        st = "[名片]";
      } else if (item.type === "connectdragon") {
        st = `[接龙]`;
      }
      //定位信息
      else if (str.address) {
        st = str.address;
      } else if (item.type === "emoji-image") {
        st = "[表情包]";
      } else {
        st = str;

        st = str.replace(/\[!(\w+)\]/gi, (str, match) => {
          console.log("解析");
          var file = match;
          return this.emojiMap[file]
            ? '<img class=\'mr-5\' style="width:18px;height:18px" emoji-name="'
                .concat(match, '" src="')
                .concat(this.emojiMap[file], '" />')
            : "[!".concat(match, "]");
        });
      }

      return st;
    },
    // ListTouch触摸开始
    ListTouchStart(e) {
      this.listTouchStart = e.touches[0].pageX;
    },
    // ListTouch计算方向
    ListTouchMove(e) {
      let cux = e.touches[0].pageX;
      let direction = cux - this.listTouchStart;
      // 左滑的距离需要达到100才能滑动出菜单,否则在页面自然滚动的时候就会吧菜单给拖出来了
      if (Math.abs(direction) > 100 && direction < 0) {
        this.listTouchDirection = "left";
      } else {
        this.listTouchDirection = "right";
      }
    },
    // ListTouch计算滚动
    ListTouchEnd(e) {
      if (this.listTouchDirection == "left") {
        this.modalName = e.currentTarget.dataset.target;
        this.chatStatus = false;
      } else {
        this.modalName = null;
      }
      this.listTouchDirection = null;
    },
    openChat(index, item) {
      // 如果左滑工具栏在开启的情况下不能够点击进入聊天
      if (this.chatStatus) {
        this.$emit("itemTap", index, item);
      } else {
        this.chatStatus = true;
      }
    },
    from_time(time) {
      return this.$util.timeFormat(time);
    },
    btnTap(index, item) {
      this.$emit("btnTap", index, item);
    },
    tiemForat(timestamp) {
      var date = new Date(timestamp);
      var hours = date.getHours();
      var minutes = date.getMinutes();
      var seconds = date.getSeconds();

      // 如果需要，可以在小于10的数字前加上0
      hours = hours < 10 ? "0" + hours : hours;
      minutes = minutes < 10 ? "0" + minutes : minutes;
      return hours + ":" + minutes;
    },
  },
};
</script>
<style lang="scss">
.last-time {
  position: absolute;
  top: 20rpx;
  right: 32rpx;
  color: #aeaeae;
}
.text-grey {
  color: #b3b3b3;
}
.text-overflow ::v-deep uni-text,
.text-overflow ::v-deep uni-text span {
  overflow: hidden !important;
  text-overflow: ellipsis;
  white-space: nowrap !important;
  // width: 300rpx;
  display: block;
}
.top-contacts {
  background-color: #f5f5f5 !important;
}
.cu-list {
  width: 100%;
  /* margin-top: 20rpx; */
}
.cu-list.menu-avatar > .cu-item {
  padding-right: 30rpx;
}
.no-click {
  pointer-events: none;
}
.cu-header-img {
  position: relative;
}
.cu-header-img .status-point {
  position: absolute;
  top: -4rpx;
  left: -12rpx;
  width: 16rpx;
  height: 16rpx;
}
.bg-pink {
  background-color: #1a66ff;
}
.f-w {
  font-family: PingFang SC, PingFang SC;
  font-weight: 500;
  color: #1a1a1a;
}
.item-level__wrap {
  display: flex;
  align-items: center;
}
.level-icon-wrap {
  display: flex;
  align-items: center;
  color: #22436d;
  font-size: 24rpx;
  margin-left: 15rpx;

  .level-icon {
    width: 40rpx !important;
  }
}
</style>
